package com.booter.ws.config;

import com.booter.common.HttpConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author lcw
 * @date 2023/8/16 18:40
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Bean
    public CloseableHttpClient httpClient() {
        HttpConnectionManager hm = new HttpConnectionManager();
        hm.init();
        return hm.getHttpClient();
    }

    @Bean
    public ResponseRewriteFilter filter() {
        return new ResponseRewriteFilter();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(filter());
        bean.addUrlPatterns("/*");
        bean.setAsyncSupported(true);
        return bean;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射本地路径
        registry.addResourceHandler("/attach/**").addResourceLocations("file:" + "/Users/lichunwen/Downloads/");
    }

    /**
     * 编程式校验
     * 注入javax.validation.Validator对象，然后再调用其api。
     * @return
     */
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 快速失败模式
                .failFast(true)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}
